using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Collections;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace winCRM4QueryBuilder
{
    public partial class frmCRM4XMLQueryBuilder : Form
    {
        clUtility myUtility = new clUtility();

        appsets myappsets = new appsets();

        public frmCRM4XMLQueryBuilder()
        {
            InitializeComponent();
            this.comboEntitiesList.DataSource = myUtility.GetAllCrmEntities();
            this.comboEntitiesList.DisplayMember = "colname";
            this.comboEntitiesList.ValueMember = "colname";
        }

        public frmCRM4XMLQueryBuilder(ArrayList myArraylist)
        {
            InitializeComponent();
            foreach (object me in myArraylist)
            {
                this.treeviewEntitiesAttributes.Nodes.Add(me.ToString());
            }
        }

        private void btmFetchAttributesByEntity_Click(object sender, EventArgs e)
        {
           
        }

        private ArrayList mytreearraylist;

        public ArrayList myTreeArrayList
        {
            get
            {
                return mytreearraylist;
            }
            set
            {
                mytreearraylist = value;
            }
        }

        public void UpdateTree()
        {
            int iIndex = 0;
            if (this.listviewallentities.SelectedIndices.Count > 0)
            {
                iIndex = this.listviewallentities.SelectedIndices[0];
            }
            this.treeviewEntitiesAttributes.BeginUpdate();
            this.treeviewEntitiesAttributes.Nodes.Add(listviewallentities.Items[iIndex].Text.ToString());

            int iNodeCount;
            iNodeCount = this.treeviewEntitiesAttributes.Nodes.Count - 1; 
            foreach (object me in mytreearraylist)
            {
                this.treeviewEntitiesAttributes.Nodes[iNodeCount].Nodes.Add(me.ToString());
            }
            this.treeviewEntitiesAttributes.EndUpdate();
        }


        private void listviewallentities_DoubleClick(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection collitems = this.listviewallentities.SelectedItems;
            foreach (ListViewItem item in collitems){
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.OrganizationName = "JEFCHI";
                token.AuthenticationType = 0;
                MetadataService metadataService = new MetadataService();
                //metadataService.Url = "http://moss:5555/MSCrmServices/2007/MetadataService.asmx";
                metadataService.Url =myappsets.crmserverurl + "MSCrmServices/2007/MetadataService.asmx";
                metadataService.CrmAuthenticationTokenValue = token;
                metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                metadataService.PreAuthenticate = true;
                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.LogicalName = item.SubItems[0].Text;
                request.EntityItems = EntityItems.IncludeAttributes;
                RetrieveEntityResponse response = (RetrieveEntityResponse)metadataService.Execute(request);
                EntityMetadata entityMetadata = response.EntityMetadata;
                foreach (Form frm in this.MdiChildren)
                {
                    if (frm is frmCRM4XMLQueryBuilderAttributeLK)
                    {
                        frm.Focus();
                        return;
                    }
                }
                frmCRM4XMLQueryBuilderAttributeLK myform2 = new frmCRM4XMLQueryBuilderAttributeLK(entityMetadata, this);
                myform2.Show();
            }
        }

        private void btnAddEntityToQueryList_Click(object sender, EventArgs e)
        {
            if (this.listviewallentities.Items.Count > 0)
            {
                MessageBox.Show("sorry this version only support query against one entity...");
            }
            else
            {
                this.listviewallentities.Items.Add(comboEntitiesList.SelectedValue.ToString(), comboEntitiesList.SelectedIndex);
            }
        }

        private void btnGenerateQuery_Click(object sender, EventArgs e)
        {
            StringBuilder mysb = new StringBuilder();
            mysb.Append(@"<fetch mapping='logical'>");
            foreach (TreeNode myNode in this.treeviewEntitiesAttributes.Nodes)
            {
                mysb.Append(@"<entity name='" + myNode.Text.ToString() + "'>");
                foreach (TreeNode tn in myNode.Nodes)
                {
                    mysb.Append(@"<attribute name='" + tn.Text.ToString() + "'/>  ");
                }
                mysb.Append(@"</entity>");
            }
            mysb.Append(@"</fetch>");
            this.richtextboxquery.Text = mysb.ToString();
        }


        private void treenoderecurisev(TreeNode treenode)
        {
            foreach (TreeNode tn in treenode.Nodes)
            {
                treenoderecurisev(tn);
            }
        }

        private void richtextboxquery_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                contextMenuStrip1.Show(richtextboxquery, new Point(e.X, e.Y));
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(richtextboxquery.SelectedText);
            MessageBox.Show("Code Copied");
        }


        private void testQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmCRM4XMLQueryTestQuery myform3 = new frmCRM4XMLQueryTestQuery(this.richtextboxquery.Text);
            myform3.Show();
        }
    }
}